package com.haierCamera.customapplication.ui.user.activity;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.haierCamera.customapplication.Constants;
import com.haierCamera.customapplication.R;
import com.haierCamera.customapplication.api.repo.RegisterRepo;
import com.haierCamera.customapplication.api.repo.UserRepo;
import com.haierCamera.customapplication.api.vo.GetUserInfoResponse;
import com.haierCamera.customapplication.common.Resource;
import com.haierCamera.customapplication.databinding.HzklActivityUserInfoBinding;
import com.haierCamera.customapplication.BaseActivity;
import com.haierCamera.customapplication.ui.login.HZKLLoginActivity;
import com.haierCamera.customapplication.ui.login.HZKLLoginWelcomeActivity;
import com.haierCamera.customapplication.utils.BitmapUtils;
import com.haierCamera.customapplication.utils.SharedPreferencesUtils;
import com.haierCamera.customapplication.utils.android.ActivityManager;
import com.haierCamera.customapplication.utils.android.HttpErrorProcess;
import com.haierCamera.customapplication.utils.glide.Glide4Engine;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.internal.entity.CaptureStrategy;
import com.zhihu.matisse.internal.utils.MediaStoreCompat;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.inject.Inject;

import dagger.Lazy;

public class HZKLUserInfoActivity extends BaseActivity {
    private static final int REQUEST_CODE_CHOOSE = 0x01;
    private static final int REQUEST_CODE_CHOOSE_PHOTO_SHOOT = 0x100;
    private static final String TAG = "HZKLUserInfoActivity";
    private HzklActivityUserInfoBinding binding;
    @Inject
    UserRepo repo;
    List<Uri> list = new ArrayList<>();
    @Inject
    RegisterRepo registerRepo;
    @Inject
    Lazy<HttpErrorProcess> errorProcessLazy;
    private MediaStoreCompat mediaStoreCompat;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.hzkl_activity_user_info);
        initData();
    }

    private void initData() {
        binding.registerBack.setOnClickListener(v -> finish());
        binding.userNameLayout.setOnClickListener(view -> startActivity(new Intent(HZKLUserInfoActivity.this, HZKLUserNameActivity.class)));
        binding.userPhoneBtn.setOnClickListener(view -> setPhone());
        binding.iconLayout.setOnClickListener(view -> showDialog());
        binding.userWXBtn.setOnClickListener(view -> removeBinding());
    }

    private void removeBinding() {
        new AlertDialog.Builder(HZKLUserInfoActivity.this).setMessage("确定解绑该账号")
                .setNegativeButton("取消", (dialogInterface, i) -> dialogInterface.dismiss()).setPositiveButton("确定", (dialogInterface, i) -> {
            dialogInterface.dismiss();
            showWX();
        }).show();
    }

    private void showWX() {
        registerRepo.removeWX("0").observe(this, objectResource -> {
            switch (objectResource.status) {
                case LOADING:
                    showLoadingDialog();
                    break;
                case ERROR:
                    dismissLoadingDialog();
                    errorProcessLazy.get().process(objectResource);
                    break;
                case SUCCESS:
                    SharedPreferencesUtils.remove(Constants.SP_USER_TOKEN);
                    SharedPreferencesUtils.remove(Constants.SP_USER_PHONE);
                    SharedPreferencesUtils.remove(Constants.SP_USER_HEAD_URL);
                    startActivity(new Intent(HZKLUserInfoActivity.this, HZKLLoginWelcomeActivity.class));
                    finish();
                    break;
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        getUser();
    }

    private void showDialog() {
        Dialog dialog = new Dialog(this);
        Window window = dialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        //window.getDecorView().setPadding(-10, 0, -10, -10);
        View view = View.inflate(this, R.layout.hzkl_dialog_camera, null);
        dialog.setContentView(view);
        Button cancel = view.findViewById(R.id.cancel);
        Button photo = view.findViewById(R.id.photo);
        Button camera = view.findViewById(R.id.camera);
        cancel.setOnClickListener(v -> dialog.dismiss());
        photo.setOnClickListener(v -> {
            upIcon();
            dialog.dismiss();
        });
        camera.setOnClickListener(v -> {
            processWithPermission(() -> processWithPermission(() -> {
                mediaStoreCompat = new MediaStoreCompat(HZKLUserInfoActivity.this);
                mediaStoreCompat.setCaptureStrategy(new CaptureStrategy(true, "com.haierCamera.customapplication.fileProvider"));
                mediaStoreCompat.dispatchCaptureIntent(HZKLUserInfoActivity.this, REQUEST_CODE_CHOOSE_PHOTO_SHOOT);
            }, Manifest.permission.CAMERA), Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE);
            dialog.dismiss();
        });
        dialog.show();
        window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
    }

    private void upIcon() {
        Set<MimeType> set = new HashSet<>();
        set.add(MimeType.JPEG);
        set.add(MimeType.PNG);
        set.add(MimeType.BMP);
        processWithPermission(() -> processWithPermission(() -> {
            Matisse.from(HZKLUserInfoActivity.this)
                    .choose(set)
                    .countable(true)
                    .spanCount(3)
                    /* .capture(true)
                     .captureStrategy(new CaptureStrategy(true, "com.haierCamera.customapplication.fileProvider"))*/
                    // .theme(R.style.MatisseStyle)
                    .maxSelectable(1)
                    .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                    .thumbnailScale(0.85f)
                    .imageEngine(new Glide4Engine())
                    .forResult(REQUEST_CODE_CHOOSE);

        }, Manifest.permission.CAMERA), Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE);
    }

    private void getUser() {
        repo.getUserInfo().observe(this, getUserInfoResource -> {
            switch (getUserInfoResource.status) {
                case LOADING:
                    break;
                case ERROR:
                    errorProcessLazy.get().process(getUserInfoResource);
                    break;
                case SUCCESS:
                    GetUserInfoResponse data = getUserInfoResource.data;
                    assert data != null;
                    binding.userPhonne.setText(data.mobile);
                    binding.userName.setText(data.nickName);
                    Glide.with(this).load(data.headUrl).apply(new RequestOptions().error(R.drawable.hzkl_user_icon).circleCrop()).into(binding.userIcon);
                    //	登录模式 -1=密码登录 0=微信登录 1=QQ登录
                    if (!data.oauthType.equals("-1")) {
                        binding.userWXLayout.setVisibility(View.VISIBLE);
                        if (data.oauthType.equals("0")) {
                            binding.userWXTitle.setText("微信");
                            binding.userWXNum.setText(data.nickName);
                        } else {
                            //binding.userWXTitle.setText("微信");
                        }
                    } else {
                        binding.userWXLayout.setVisibility(View.GONE);
                    }
                    break;
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE_CHOOSE:
                    List<Uri> mSelected = Matisse.obtainResult(data);
                    Log.d("Matisse", "mSelected: " + mSelected);
                    list.clear();
                    list.addAll(mSelected);
                    if (list.size() == 0) {
                        return;
                    }
                    upSevice();
                    break;
                case REQUEST_CODE_CHOOSE_PHOTO_SHOOT:
                    //因为是指定Uri所以onActivityResult中的data为空 只能再这里获取拍照的路径
                    Uri currentPhotoPath = mediaStoreCompat.getCurrentPhotoUri();
                    Log.e(TAG, "showDialog:==== " + currentPhotoPath);
                    list.clear();
                    list.add(currentPhotoPath);
                    if (list.size() == 0) {
                        return;
                    }
                    upSevice();
                    break;
                default:
                    break;
            }
        }
    }

    private void upSevice() {
        List<Bitmap> images = new ArrayList<>();
        for (Uri uri : list) {
            try {
                Bitmap bitmap = BitmapUtils.getBitmapFormUri(this, uri);
                images.add(bitmap);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        repo.publicUpImage(images).observe(this, stringResource -> {
            switch (stringResource.status) {
                case LOADING:
                    showLoadingDialog();
                    break;
                case ERROR:
                    dismissLoadingDialog();
                    //Toast.makeText(this, stringResource.errorMessage, Toast.LENGTH_SHORT).show();
                    errorProcessLazy.get().process(stringResource);
                    break;
                case SUCCESS:
                    upImage(stringResource.data);
                    break;
            }
        });
    }

    private void upImage(String data) {
        repo.upHead(data).observe(this, objectResource -> {
            switch (objectResource.status) {
                case LOADING:
                    break;
                case ERROR:
                    dismissLoadingDialog();
                    //Toast.makeText(HZKLUserInfoActivity.this, objectResource.errorMessage, Toast.LENGTH_SHORT).show();
                    errorProcessLazy.get().process(objectResource);
                    break;
                case SUCCESS:
                    dismissLoadingDialog();
                    Toast.makeText(HZKLUserInfoActivity.this, "上传成功", Toast.LENGTH_SHORT).show();
                    Glide.with(this).load(data).apply(new RequestOptions().circleCrop()).into(binding.userIcon);

                    SharedPreferencesUtils.saveString(Constants.SP_USER_HEAD_URL, data);
                    list.clear();
                    break;
            }
        });
    }

    private void setPhone() {
        String phone = binding.userPhonne.getText().toString();
        registerRepo.getVcode(phone).observe(this, objectResource -> {
            switch (objectResource.status) {
                case LOADING:
                    break;
                case ERROR:
                    //Toast.makeText(HZKLUserInfoActivity.this, objectResource.errorMessage, Toast.LENGTH_SHORT).show();
                    errorProcessLazy.get().process(objectResource);
                    break;
                case SUCCESS:
                    startActivityForResult(new Intent(HZKLUserInfoActivity.this, HZKLUserCheckPhoneActivity.class)
                            .putExtra("phone", phone).putExtra("title", "验证手机号"), 100);
                    break;
            }
        });
    }
}
